﻿#include "ThreadControl.h"
#include <QThread>
#include "ThreadTask.h"
#include "BaseModule/GlobalHelper.h"

namespace BaseWidget
{
    ThreadControl::ThreadControl(ThreadTask* task)
        : m_threadTask(task)
    {
        m_thread = new QThread;
        m_threadTask->moveToThread(m_thread);

        connect(this, &ThreadControl::signal_threadStop, m_threadTask, &ThreadTask::stop);
        connect(m_threadTask, &ThreadTask::signal_startThread, this, &ThreadControl::slot_startThread);
        connect(m_threadTask, &ThreadTask::signal_threadFinished, this, &ThreadControl::slot_deleteThread);
        connect(m_threadTask, &ThreadTask::signal_sleepThread, this, &ThreadControl::slot_sleepThread);
        connect(m_thread, &QThread::finished, m_threadTask, &QObject::deleteLater);
        connect(m_thread, &QThread::finished, m_thread, &QObject::deleteLater);

    }

    ThreadControl::~ThreadControl()
    {
        m_thread->quit();
        m_thread->wait();
    }

    QString ThreadControl::getUUID()
    {
        return m_uuid;
    }
    
    void ThreadControl::slot_startThread()
    {
        m_thread->start();
    }

    void ThreadControl::slot_deleteThread()
    {
        this->signal_removeThread(m_uuid);
        delete this;
    }

    void ThreadControl::slot_sleepThread(int msec)
    {
        m_thread->msleep(msec);//线程休眠毫秒，主线程堵塞
    }

}
